﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace TaxiDispatchClient
{
    using System.Globalization;

    using DevExpress.XtraBars;

    /// <summary>
    /// 音频管理form
    /// </summary>
    public partial class AudioMgrForm : XtraForm
    {
        /// <summary>
        /// 存放音频文件的目录
        /// </summary>
        private  string audioDir ;

        /// <summary>
        /// 带路径的文件列表
        /// </summary>
        private List<string> fullFileNames = new List<string>();

        /// <summary>
        /// 文件名列表
        /// </summary>
        private ArrayList fileNameList = new ArrayList();

        /// <summary>
        /// 构造函数
        /// </summary>
        public AudioMgrForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 更新树节点
        /// </summary>
        /// <param name="node">要更新的节点</param>
        private void NodeUpdate(TreeNode node)
        {
            try
            {
                node.Nodes.Clear();
                string path = audioDir.Remove(audioDir.LastIndexOf(@"\")) + "\\"
                    + node.FullPath;
                DirectoryInfo dir = new DirectoryInfo(path);
                //DirectoryInfo dir = new DirectoryInfo(node.FullPath);            
                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo d in dirs)
                {
                    TreeNode newNode = node.Nodes.Add(d.Name, d.Name);
                    newNode.ImageIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("NodeUpdate:"+ex.Message);
            }           
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void AudioMgrForm_Load(object sender, EventArgs e)
        {
            try
            {
                string strPath = Application.ExecutablePath;
                strPath = strPath.Remove(strPath.LastIndexOf(@"\"));
                audioDir = strPath + @"\Record";
                //= Application.ExecutablePath.Remove() + @"\Record"

                Common.LogService.WriteLog(audioDir);
                if (!Directory.Exists(audioDir))
                {
                    Directory.CreateDirectory(audioDir);
                }

                TreeNode node = treeView1.Nodes.Add("Record");
                node.ImageIndex = 0;
                NodeUpdate(node);
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("Form_Load:"+ex.Message);
            }
           
        }

        /// <summary>
        /// 获取指定目录文件的文件并显示到List
        /// </summary>
        /// <param name="dir">目录路径</param>
        private void GenerateFileList(string dir)
        {
            try
            {
                listView1.BeginUpdate();
                listView1.Items.Clear();
                
                dir = audioDir.Remove(audioDir.LastIndexOf("\\"))
                    +"\\"+dir;


                DirectoryInfo dires = new DirectoryInfo(dir);
                DirectoryInfo[] dirs = dires.GetDirectories(); ////获取目录

                foreach (DirectoryInfo subdir in dirs)
                {
                    ListViewItem dirItem = listView1.Items.Add(subdir.Name, 1);
                    dirItem.Name = subdir.FullName;
                    dirItem.SubItems.Add(string.Empty);
                    dirItem.SubItems.Add("文件夹");
                    dirItem.SubItems.Add(subdir.LastWriteTimeUtc.ToString(CultureInfo.InvariantCulture));
                }

                FileInfo[] files = dires.GetFiles();
                foreach (FileInfo f in files)
                {
                    ListViewItem fileItem = listView1.Items.Add(f.Name, 0);
                    fileItem.Name = f.FullName;
                }

                listView1.EndUpdate();
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("GenerateFileList:"+ex.Message);
            }           
        }

        /// <summary>
        /// 删除按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    if (XtraMessageBox.Show("确定删除选择的录音文件？", "警告", MessageBoxButtons.YesNo) == DialogResult.No)
                        return;
                    foreach (ListViewItem item in listView1.SelectedItems)
                    {
                        try
                        {
                            if (File.Exists(item.Name))
                            {
                                File.Delete(item.Name);
                            }

                            if (Directory.Exists(item.Name))
                            {
                                Directory.Delete(item.Name, true);
                                treeView1.SelectedNode.Nodes[item.Text].Remove();
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.CommonRoutine.HandlingExceptions(ex, true);
                        }
                        fullFileNames.Remove(item.Name);
                        listView1.Items.Remove(item);
                        //treeView1.Nodes.Remove();
                    }
                }

            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("barButtonItem2_ItemClick:"
                    +ex.Message);  
            }
          
        }

        /// <summary>
        /// 列表项激活事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void listView1_ItemActivate(object sender, EventArgs e)
        {
            try
            {
                if (listView1.SelectedItems.Count > 0)
                {
                     string newPath = listView1.SelectedItems[0].Name;
                    
                    if (Directory.Exists(newPath))
                    {
                        GenerateFileList(newPath);
                    }
                    else
                    {
                        string fileFullName = listView1.SelectedItems[0].Name;

                        if (File.Exists(fileFullName))
                        {
                            try
                            {
                                axWindowsMediaPlayer1.URL = fileFullName;
                                axWindowsMediaPlayer1.Ctlcontrols.play();
                            }
                            catch (Exception ex)
                            {
                                Common.CommonRoutine.HandlingExceptions(ex, true);
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("文件不存在");
                        }
                    }
                }
            }
            catch (Exception ex )
            {
                Common.LogService.WriteLog("listView1_ItemActivate:" + ex.Message);             
            }
      
        }

        /// <summary>
        /// 更改选定内容事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                e.Node.Expand();
                if (radioGroup1.SelectedIndex == 0)
                {
                    GenerateFileList(e.Node.FullPath);
                }
                else
                {
                    listView1.Items.Clear();

                    foreach (string t in fullFileNames)
                    {
                        string filename = Path.GetFileName(t);
                        if (filename.Length > 7)
                        {
                            if (filename.Substring(0, 7) == e.Node.Text)
                            {
                                ListViewItem fileItem = listView1.Items.Add(filename, 0);
                                fileItem.Name = t;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("AfterSelect:" + ex.Message);
            }
           
        }

        /// <summary>
        /// 展开节点事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                if (radioGroup1.SelectedIndex == 0)
                {
                    NodeUpdate(e.Node); ////更新当前结点
                    foreach (TreeNode node in e.Node.Nodes)
                    {
                        NodeUpdate(node);
                    }
                }
                else
                {
                    if (e.Node.Parent == null)
                    {
                        e.Node.Nodes.Clear();
                        fullFileNames.Clear();
                        fileNameList.Clear();

                        DirectoryInfo dir = new DirectoryInfo(audioDir);
                        DirectoryInfo[] dirs = dir.GetDirectories();
                        foreach (DirectoryInfo folder in dirs)
                        {
                            foreach (FileInfo nextFile in folder.GetFiles())
                            {
                                fullFileNames.Add(nextFile.FullName);
                                if (nextFile.Name.Length > 8)
                                {
                                    string carPlate = nextFile.Name.Substring(0, 7);
                                    if (fileNameList.IndexOf(carPlate) < 0)
                                    {
                                        fileNameList.Add(carPlate);
                                    }
                                }
                            }
                        }

                        foreach (string carPlate in fileNameList)
                        {
                            e.Node.Nodes.Add(carPlate);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("BeforeExpand:"+ex.Message);
            }
            
        }

        /// <summary>
        /// 复制按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string[] sources = new string[listView1.SelectedItems.Count];
                int i = 0;
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    sources[i++] = item.Name;
                }

                IDataObject data = new DataObject(DataFormats.FileDrop, sources);
                MemoryStream memo = new MemoryStream(4);
                byte[] bytes = new byte[] { 5, 0, 0, 0 };
                memo.Write(bytes, 0, bytes.Length);
                data.SetData("Preferred DropEffect", memo);
                Clipboard.SetDataObject(data);
            }
        }

        /// <summary>
        /// radioGroup选择项改变事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                treeView1.Nodes.Clear();
                listView1.Items.Clear();

                if (radioGroup1.SelectedIndex == 0)
                {
                    TreeNode node = treeView1.Nodes.Add("Record");
                    NodeUpdate(node);
                }
                else
                {
                    fullFileNames.Clear();
                    fileNameList.Clear();

                    DirectoryInfo dir = new DirectoryInfo(audioDir);
                    DirectoryInfo[] dirs = dir.GetDirectories();
                    foreach (DirectoryInfo folder in dirs)
                    {
                        foreach (FileInfo nextFile in folder.GetFiles())
                        {
                            fullFileNames.Add(nextFile.FullName);
                            if (nextFile.Name.Length > 8)
                            {
                                string carPlate = nextFile.Name.Substring(0, 7);
                                if (fileNameList.IndexOf(carPlate) < 0)
                                {
                                    fileNameList.Add(carPlate);
                                }
                            }
                        }
                    }

                    TreeNode node = treeView1.Nodes.Add("Record");

                    foreach (string carPlate in fileNameList)
                    {
                        node.Nodes.Add(carPlate);
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("radiogroup:"+ex.Message);
            }
          
        }

        /// <summary>
        /// 文件列表项选定状态改变事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            try
            {
                if (e.IsSelected && listView1.SelectedItems.Count == 1)
                {
                    string fileFullName = e.Item.Name;

                    if (File.Exists(fileFullName))
                    {
                        axWindowsMediaPlayer1.URL = fileFullName;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogService.WriteLog("ItemSelectionChanged:"+ex.Message);
            }
            
        }

        /// <summary>
        /// 全选按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (listView1.Items.Count <= 0)
            {
                return;
            }

            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Selected = true;
            }
        }

        /// <summary>
        /// 释放鼠标事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
                popupMenu1.ShowPopup(p);
                bBtnI_Copy.Enabled = listView1.SelectedItems.Count != 0;
                bBtnI_Del.Enabled = listView1.SelectedItems.Count != 0;
            }
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void AudioMgrForm_MouseClick(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
    }
}